package com.boarsoft.boar.deploy.app.prometheus;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boarsoft.agent.AgentService;
import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.app.AppBiz;
import com.boarsoft.boar.app.AppInstBiz;
import com.boarsoft.boar.config.service.ConfigFileService;
import com.boarsoft.boar.deploy.plan.bean.BuildRequest;
import com.boarsoft.boar.entity.AppInst;
import com.boarsoft.boar.entity.FileInfo;
import com.boarsoft.boar.entity.FileVersion;
import com.boarsoft.boar.entity.ObjLabel;
import com.boarsoft.boar.file.FileBiz;
import com.boarsoft.boar.label.ObjLabelBiz;
import com.boarsoft.boar.service.FileService;
import com.boarsoft.common.util.InetUtil;
import com.boarsoft.flow.core.bean.ProcessHandler;

/**
 * Prometheus节点宕机后，修改其上层节点的children.json<br/>
 * 更新其要抓取的下层节点的列表
 * 
 * @author Mac_J
 *
 */
public class UpdPromFedPH implements ProcessHandler {
	private static final Logger log = LoggerFactory.getLogger(UpdPromFedPH.class);

	@Autowired
	@Lazy(value = true)
	@Qualifier("agentX")
	protected AgentService agentX;
	@Autowired
	protected ConfigFileService configFileSvc;
	@Autowired
	protected FileService fileSvc;
	@Autowired
	protected FileBiz fileBiz;
	@Autowired
	protected AppBiz appBiz;
	@Autowired
	protected AppInstBiz appInstBiz;
	@Autowired
	protected ObjLabelBiz objLabelBiz;

	// prometheus.yml
	protected String fileId = "40284e817240fb1b01724180c224000c";

	@Override
	public Object process(String entry, Object data, Throwable throwable) throws Throwable {
		BuildRequest br = (BuildRequest) data;
		AppInst inst1 = (AppInst) br.get("inst1"); // old target
//		AppInst inst2 = (AppInst) br.get("inst2"); // new target
		String id1 = inst1.getId();
		// 根据宕机的节点ID，查找它的上级节点
		ObjLabel lb = objLabelBiz.find(id1, "prometheus.parent", ObjLabel.TYPE_APP_INST);
		if (lb == null) {
			throw new IllegalStateException(String.format(//
					"Label prometheus.parent of app inst %s is missing", id1));
		}
		String paiId = lb.getValue();
		AppInst pai = appInstBiz.get(paiId);
		// 查询应抓取的下级节点
		List<ObjLabel> lbLt = objLabelBiz.list(ObjLabel.TYPE_APP_INST, "prometheus.parent", paiId);
		JSONArray ja = new JSONArray();
		JSONObject jo = new JSONObject();
		ja.add(jo);
		List<String> targets = new ArrayList<>();
		jo.put("targets", targets);
		for (ObjLabel o : lbLt) {
			AppInst ai = appInstBiz.get(o.getObjId());
			targets.add(ai.getAddr());
		}
		lb = objLabelBiz.find(paiId, "prometheus.labels", ObjLabel.TYPE_APP_INST);
		if (lb != null) {
			jo.put("labels", JSONObject.parseObject(//
					lb.getValue(), JSONObject.class));
		}
		ja.add(jo);
		// [{
		// "targets": [
		// "172.16.0.96:19100"
		// ],
		// "labels": {
		// "project_name": "项目测试20200413",
		// "env_name": "开发环境",
		// "soft_name": "测试应用20200413",
		// "template_name": "测试模板20200413",
		// "template_type": "主机模板"
		// }
		// }]
		// 上传新版配置children.json到配置中心
		FileInfo fi = fileBiz.get(fileId);
		byte[] ba = ja.toJSONString().getBytes(fi.getCharset());
		ReplyInfo<Object> ro = fileSvc.commit(InetUtil.getAddr(), //
				fileId, pai.getEnv(), pai.getGroup(), ba);
		if (ro.isSuccess()) {
			// 获取新版文件的ID
			FileVersion nv = (FileVersion) ro.getData();
			// 请求配置中心下发配置
			configFileSvc.sync2(nv.getId(), pai.getAppId(), pai.getId());
		}
		return data;
	}

	public String getFileId() {
		return fileId;
	}

	public void setFileId(String fileId) {
		this.fileId = fileId;
	}
}